<?php
/**
 * User: 1971229701@qq.com
 * Date: 2020/11/3/003
 * Time: 13:11
 */

namespace app\admin\logic;


use app\common\logic\AliOss;
use app\common\logic\BaseLogic;

class UploadLogic extends BaseLogic
{
    private $allow_type = [
        '.jpg', '.jpeg', '.gif', '.bmp', '.png','.mp4','.JPG','.JPEG'
    ];

    private $file_size = 1024 * 1000;
    /**
     * oss文件上传
     * @param $files
     * @return array|false
     */
    public function uploads($files)
    {

        if (is_array($files)) {
            $r = $this->many_uploads($files);
        } else {
            $r = $this->one_upload($files);
        }

        return $r;
    }

    // 多图上传
    protected function many_uploads($files)
    {
        $data = [];
        foreach ($files as $file) {
            if ($file) {
                $name = $file->getInfo('name');
                $tmp_name = $file->getInfo('tmp_name');

                $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)

                /*判断图片格式*/
                $allow_type = $this->allow_type;

                if (!in_array($format, $allow_type)) {
                    $this->error = '文件格式不在允许范围内哦';
                    return false;
                }

                $ossUrl = $this->oss_upload($format, $tmp_name);
                $data[] = [
                    'file_url' => $ossUrl,
                    //'file_name' => basename($ossUrl)
                ];
            }
        }
        return $data;
    }

    // 单图上传
    protected function one_upload($file)
    {
        set_time_limit(0);
        $data = [];
        $name = $file->getInfo('name');
        $tmp_name = $file->getInfo('tmp_name');
        $file_size = $file->getInfo('size');
        $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)

        /*判断图片格式*/
        $allow_type = $this->allow_type;

        if (!in_array($format, $allow_type)) {
            $this->error = '文件格式不在允许范围内哦';
            return false;
        }

//        if ($file_size > $this->file_size){
//            $this->error = '文件上传过大！';
//            return false;
//        }

        $ossUrl = $this->oss_upload($format, $tmp_name);
        $data[] = [
            'file_url' => $ossUrl,
            //'file_name' => basename($ossUrl)
        ];
        return $data;
    }

    // oss 图片上传
    protected function oss_upload($format, $tmp_name)
    {
        // 定义文件存储的oss位置
        $ossPath = 'zhongcheng/' . date('Y-m-d') . '/' . date('Hi') . mt_rand(10000, 99999);
        // 定义oss object  设置文件名称。
        $object = $ossPath . $format;

        $ossClient = AliOss::getOssClient();
        $bucketName = AliOss::getBucketName();

        $res = $ossClient->uploadFile($bucketName, $object, $tmp_name);
        $ossUrl = $res['oss-request-url'];

        // 如果图片的协议是http，则转换成https
        if (substr($ossUrl, 0, 4) == 'http') {
            $ossUrl = substr_replace($ossUrl, 'https', 0, 4);
        }
        return $ossUrl;
    }
}